package com.kgc.bigdata.spark.sql

import java.util.Random

import com.kgc.bigdata.spark.sql.DataFrameRDDApp.Person
import org.apache.spark.{SparkConf, SparkContext}

/**
  * 作业：实现添加10以内随机前缀的功能，比如输入：SPARK，输出：xxx_SPARK
  */
object UDFAddPrefixApp {

  def main(args: Array[String]) {
    val sparkConf = new SparkConf().setMaster("local[2]").setAppName("UDFFunctionApp")

    val sc = new SparkContext(sparkConf)
    val sqlContext = new org.apache.spark.sql.SQLContext(sc)

    val info = sqlContext.read.format("text").load("H:/workspace/SparkProject/src/data/courses.data")
      .toDF("name")

    import org.apache.spark.sql.functions._

    //添加随机前缀
    def addRandomPrefixUDF(num: Int) = udf((content: String) => {
      val randNum = new Random().nextInt(num)
      if (randNum == 0) {
        1 + "_" + content
      } else {
        randNum + "_" + content
      }
    }
    )

    info.select(info.col("name"),addRandomPrefixUDF(10)(info.col("name"))).show

    sc.stop
  }

  case class Course(name:String)
}
